/**
 * Created by LeungZ on 2016/3/22.
 */
class CommonSrv {
    constructor($http, $q, $state, $rootScope) {
        return function (method, link, data) {
            //link = "http://132.122.239.4:8083" + link;
            let deferred = $q.defer();
            let req = {
                method: method,
                url: link
            };
            if (method == 'form') {
                req.method = 'post';
                req.data = data;
                req.headers = {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                };
                req.transformRequest = function(){
                    return angular.element.param(data);
                }
            }
            if (method == 'formData') {
                req.method = 'post';
                req.transformRequest = angular.identity;
                req.headers = {'Content-Type': undefined};
                req.data = data;
            }
            if (method == 'post' || method == 'put') {
                req.data = data
            }
            if (method == 'get') {
                req.params = data
            }
            $http(req).then(function (resp) {
                if (resp.data.resultCode == '1000' || resp.data.resultCode == '200') {
                    deferred.resolve(resp.data.data);
                } else {
                    if (resp.data.resultCode == '403') {
                        $rootScope.user = null;
                        $state.transitionTo('login', '', {
                            reload: true,
                            inherit: false,
                            notify: true
                        });
                        return;
                    }
                    deferred.reject(resp.data)
                }
            }, function () {
                deferred.reject({resultMsg: '网络连接失败'});
            });
            return deferred.promise;
        }
    }

    static factory($http, $q, $state, $rootScope) {
        "ngInject";
        return new CommonSrv($http, $q, $state, $rootScope);
    }
}
export default CommonSrv